/**
 * 
 */
package it.unisalento.appsalento.asynctask;

import it.unisalento.appsalento.activity.App;
import it.unisalento.appsalento.asynctask.framework.MIMETypes;
import it.unisalento.appsalento.constants.Constants;
import it.unisalento.appsalento.model.Request;
import it.unisalento.appsalento.model.Response;

import java.io.IOException;

import android.os.AsyncTask;
import android.os.Build;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

/**
 * <p>
 * <b>Description</b>: Classe che estende Async Task. Si occupa di effettuare la
 * registrazione dell'applicazione su GCM
 * </p>
 * 
 * @author Gregorio Palama
 * 
 */
public class GcmRegistrationAsyncTask extends AsyncTask<Void, Void, String> {

	@Override
	protected String doInBackground(Void... params) {
		String registrationId;
		GoogleCloudMessaging gcm;

		try {
			gcm = GoogleCloudMessaging.getInstance(App.currentActivity()
					.getApplicationContext());
			registrationId = gcm.register(Constants.SENDER_ID);

			// Inviamo il registrationId al backend applicativo
			sendRegistrationIdToBackend(registrationId);

			// Salviamo il registrationId nelle shared preferences
			App.storeRegistrationId(App.currentActivity()
					.getApplicationContext(), registrationId);
		} catch (IOException ex) {
			registrationId = "";
		}
		App.registrationId = registrationId;
		return registrationId;
	}

	/**
	 * Invia al servizio rest l'id di registrazione a GCM
	 */
	private void sendRegistrationIdToBackend(String registrationId) {
		RegisterToBackendAsyncTask registerToBackendTask = new RegisterToBackendAsyncTask(
				registrationId);
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
			registerToBackendTask.executeOnExecutor(
					AsyncTask.THREAD_POOL_EXECUTOR, (Void[]) null);
		} else {
			registerToBackendTask.execute((Void[]) null);
		}
	}

	private class RegisterToBackendAsyncTask extends
			AsyncTask<Void, Void, Void> {
		private String registrationId;

		public RegisterToBackendAsyncTask(String registrationId) {
			this.registrationId = registrationId;
		}

		@Override
		protected Void doInBackground(Void... params) {
			ObjectMapper mapper = new ObjectMapper();
			try {
				setData(mapper);
			} catch (Throwable e) {
				e.printStackTrace();
			}

			return null;
		}

		public boolean setData(ObjectMapper mapper) throws JsonParseException,
				JsonMappingException, IOException {
			boolean retVal = false;
			if (!Constants.MOCK_ENABLED) {
				Request request = new Request();
				request.setUtente(App.utente);
				request.setRegistrationId(registrationId);
				final Gson gson = new GsonBuilder().create();
				final Client client = Client.create();
				final WebResource resource = client.resource(Constants.URL_REST
						+ Constants.SERVICE_REGISTRA_GCM_ID);
				final ClientResponse response = resource.type(
						MIMETypes.APPLICATION_JSON.getName()).post(
						ClientResponse.class, gson.toJson(request));

				final String responseEntity = response.getEntity(String.class)
						.replaceAll("\\\\", "");
				Response prenotazioneResponse = mapper.readValue(
						responseEntity, Response.class);
				if (prenotazioneResponse != null) {
					retVal = prenotazioneResponse.isOk();
				}
			} else {
				retVal = true;
			}
			return retVal;
		}

	}

}
